package edu.caece.langprocessor.syntax.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.caece.langprocessor.syntax.GrammarItem;
import edu.caece.langprocessor.syntax.NonTerminal;

public class Tree {
	
	private Map<TreeNode, List<TreeNode>> relations; 
	private TreeNode root = null;
	private Set<TreeNode> nodes;
	private TreeNodeFactory syntaxTreeNodeFactory;
	
	public Tree(){
		this.relations = new HashMap<TreeNode, List<TreeNode>>();
		this.nodes = new HashSet<TreeNode>();
		this.syntaxTreeNodeFactory = new TreeNodeFactory();
	}
	
	public void addChild(GrammarItem parent, GrammarItem child){

		TreeNode stnParent;
		
		if(!this.containsByGrammarItem(parent)) {
			//Si el elemento no existe en el arbol lo creo
			stnParent = this.syntaxTreeNodeFactory.getNewInstance(parent);
			this.nodes.add(stnParent);
		}else{
			stnParent = this.findByGrammarItem(parent);	
		}
		if (!this.relations.containsKey(stnParent))
			this.relations.put(stnParent, new ArrayList<TreeNode>());

		List<TreeNode> children = this.relations.get(stnParent);
		
		TreeNode stnChild;
		if(!this.containsByGrammarItem(child)) {
			stnChild = this.syntaxTreeNodeFactory.getNewInstance(child);
			this.nodes.add(stnChild);
		}else{
			stnChild = this.findByGrammarItem(child);
		}
		children.add(stnChild);
	}
	
	public void addChildByNodeType(String productionClass,
			NonTerminal parent, GrammarItem child) {
		
		TreeNode stnParent;
		
		if(!this.containsByGrammarItem(parent)) {
			//Si el elemento no existe en el arbol lo creo
			stnParent = this.syntaxTreeNodeFactory.getNewInstance(productionClass, parent);
			this.nodes.add(stnParent);
		}
		this.addChild(parent, child);
	}
	
	private boolean containsByGrammarItem(GrammarItem item) {
		Boolean found = false;
		TreeNode stn = null;
		
		Iterator<TreeNode> nodesIterator = this.nodes.iterator();
		while (!found && nodesIterator.hasNext())
		{
			stn = nodesIterator.next(); 
			found = (stn.getGrammarItem() == item);
		}
		if (!found) {stn = null;}
		return found;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Tree))
			return false;
		
		Tree other = (Tree) obj;
		if (nodes != null && other.nodes != null)
		{
			if(!this.sameNodes(this, other) || !this.sameNodes(other, this))
				return false;
		}else
			return false;
		
		if (relations != null && other.relations != null){
			if(!this.sameRelations(this, other) || !this.sameRelations(other, this))
				return false;
		} else 
			return false;

		if (!this.getRoot().equals(other.getRoot())) 
			return false;
		return true;
	}
	
	private TreeNode findByGrammarItem(GrammarItem parent) {
		Boolean found = false;
		TreeNode stn = null;
		
		Iterator<TreeNode> nodesIterator = this.nodes.iterator();
		while (!found && nodesIterator.hasNext())
		{
			stn = nodesIterator.next(); 
			found = (stn.getGrammarItem() == parent);
		}
		if (!found) 
			throw new RuntimeException("GrammarItem not found in tree!");
		return stn;
	}
	
	public List<TreeNode> getChildren(GrammarItem node){
		TreeNode stnParent = this.findByGrammarItem(node);
		return this.getChildren(stnParent);
	}
	
	public List<TreeNode> getChildren(TreeNode node){
		return this.relations.get(node);
	}

	public TreeNode getRoot() {
		this.root = setRoot();
		return this.root;
	}


	private boolean hasChildren(GrammarItem grammarItem) {
		TreeNode stnParent = this.findByGrammarItem(grammarItem);
		return this.hasChildren(stnParent);
	}

	public boolean hasChildren(TreeNode node){
		return (this.relations.get(node) != null);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((nodes == null) ? 0 : nodes.hashCode());
		result = prime * result
				+ ((relations == null) ? 0 : relations.hashCode());
		result = prime * result + ((root == null) ? 0 : root.hashCode());
		return result;
	}

	private boolean sameChildren(List<TreeNode> thisChildren, List<TreeNode> otherChildren) {
		boolean sameChildren = true;
		
		sameChildren = sameChildren && thisChildren.size() == otherChildren.size();
		for (int index = 0 ; index< thisChildren.size(); index++){
			sameChildren = sameChildren && 
							thisChildren.get(index).getGrammarItem() == 
							otherChildren.get(index).getGrammarItem();
		}
		return sameChildren;
	}

	private boolean sameNodes(Tree tree, Tree other) {
		boolean sameNodes = true;
		for (TreeNode thisNode : tree.nodes) {
			boolean exist = false;
			for (TreeNode otherNode : other.nodes) {
				exist = (otherNode.equals(thisNode));
				if(exist)
					break;
			}
			sameNodes = sameNodes && exist;
		}
		return sameNodes;
	}

	private boolean sameRelations(Tree tree, Tree other) {
		boolean sameRelations = true;
		
		for (TreeNode node : tree.nodes) {
			if(tree.hasChildren(node) && other.hasChildren(node.getGrammarItem())){
				List<TreeNode> thisChildren = tree.getChildren(node);
				List<TreeNode> otherChildren = other.getChildren(node.getGrammarItem());
				sameRelations = sameRelations && sameChildren(thisChildren, otherChildren);
			}
			else{ 
				sameRelations = sameRelations && 
					(!tree.hasChildren(node) && !other.hasChildren(node.getGrammarItem()));
			}
		}
		return sameRelations;
	}

	private TreeNode setRoot() {
		Boolean found = true;

		TreeNode stn  = this.root;
		if (stn == null){
			Iterator<TreeNode> keysIterator = relations.keySet().iterator();
			while (found && keysIterator.hasNext()) {
				found = false;
				stn = keysIterator.next(); 
				Iterator<List<TreeNode>> childrenIterator = relations.values().iterator();
				while(!found && childrenIterator.hasNext()) {
					List<TreeNode> list = childrenIterator.next();
					for (TreeNode child : list) {
						if (stn == child){
							found = true;
							break;
						}
					}
				}
			}
		}
		return stn;
	}
	
	


}
